from fastapi import APIRouter, HTTPException
from fastapi.responses import FileResponse
from ..services.download import DownloadService
from ..utils.logger import setup_logger
import os

router = APIRouter()
logger = setup_logger('download_api')

@router.get("/download/{filename}")
async def download_file(filename: str, temp_dir: str = None, type: str = "output"):
    """下载文件接口"""
    try:
        logger.info(f"收到下载请求 - 文件名: {filename}, 临时目录: {temp_dir}, 类型: {type}")
        
        # 从完整路径中提取文件名
        filename = os.path.basename(filename)
        logger.info(f"提取的文件名: {filename}")
        
        # 检查temp_dir是否存在
        if not temp_dir:
            error_msg = "缺少temp_dir参数"
            logger.error(error_msg)
            raise HTTPException(status_code=400, detail=error_msg)
            
        # 检查temp_dir目录是否存在
        if not os.path.exists(temp_dir):
            error_msg = f"临时目录不存在: {temp_dir}"
            logger.error(error_msg)
            raise HTTPException(status_code=404, detail=error_msg)
        
        # 根据type参数确定文件路径
        if type == "text":
            # OCR文本文件路径
            file_path = os.path.join(temp_dir, "ocr", "text", filename)
        else:
            # 处理结果文件路径（默认）
            file_path = os.path.join(temp_dir, "output", filename)
            
        logger.info(f"构建的文件路径: {file_path}")
        
        # 检查文件是否存在
        if not os.path.exists(file_path):
            error_msg = f"文件不存在: {file_path}"
            logger.error(error_msg)
            raise HTTPException(status_code=404, detail="文件不存在")
            
        # 检查文件是否可读
        if not os.access(file_path, os.R_OK):
            error_msg = f"文件无法读取: {file_path}"
            logger.error(error_msg)
            raise HTTPException(status_code=403, detail="文件无法读取")
        
        # 根据文件扩展名设置正确的media_type
        media_type = "text/plain" if filename.endswith('.txt') else "text/markdown"
        
        logger.info(f"准备下载文件: {file_path}, media_type: {media_type}")
        return FileResponse(
            path=file_path,
            filename=filename,
            media_type=media_type
        )
        
    except Exception as e:
        error_msg = f"文件下载失败: {str(e)}"
        logger.error(error_msg)
        raise HTTPException(status_code=500, detail=error_msg) 